package com.spring.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeanFactory {
    /* 静态代码块 调用类的时候会自动执行*/
    private static Map<String,Object> iocpom = new HashMap<>();
    static {

        try {  //1. 读取配置文件
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
            // 1.解析xml
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(in);
            /*获取路径*/
            String xpath = "//bean";

            List<Element> list = document.selectNodes(xpath);
            for (Element element : list) {
                // 获取id 值
                String id = element.attributeValue("id");
                // 获取class com.spring.dao.Impl.UserDaoImpl
                String aClass = element.attributeValue("class");
                /*反射*/
                Object object = Class.forName(aClass).newInstance();
                /* 把创建的实例对象放在容器里 put(key,value)*/
                iocpom.put(id,object);
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }


    public static Object getBean(String id){
        return  iocpom.get(id);
    }
}
